package com.slf.engine.services.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import com.slf.engine.base.IBaseDao;
import com.slf.engine.bo.TFcinfo;
import com.slf.engine.common.SysContants;
import com.slf.engine.exception.EngineException;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.http.HttpResponseWrapper;
import com.slf.engine.services.IFcjs0573Service;
import com.slf.engine.threads.HeartThread;
import com.slf.engine.utils.DateUtils;
import com.slf.engine.utils.Factory;

public class Fcjs0573ServiceImpl implements IFcjs0573Service {

	private static final Logger log = Logger.getLogger(Fcjs0573ServiceImpl.class);
	private static final String DEFAULT_CHARSET = "gbk";
	public boolean login(HttpClientManager manager)
	{
		manager.setCookiePolicy(CookiePolicy.DEFAULT);
		NameValuePair cls = new NameValuePair("cls","1");
		NameValuePair account = new NameValuePair("account",SysContants.FC_LOGINNAME);
		NameValuePair imageField_x = new NameValuePair("imageField.x","31");
		NameValuePair imageField_y = new NameValuePair("imageField.y","27");
		NameValuePair password = new NameValuePair("password",SysContants.FC_PASSWORD);
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(cls);
		params.add(account);
		params.add(imageField_x);
		params.add(imageField_y);
		params.add(password);
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/x-www-form-urlencoded");
		headers.put("Host", "fc.js0573.com");
		headers.put("Accept", "*/*");
		headers.put("Cookie", "chkCookies=1");
		try {
			HttpResponseWrapper wrapper = manager.execute("POST", "http://fc.js0573.com/signin.asp", DEFAULT_CHARSET, null, null, params, headers, null);
			if(wrapper.getBody() == null)
			{
				return login(manager);
			}
			String body = new String(wrapper.getBody(), DEFAULT_CHARSET);
			if(body.indexOf("嘉善房产网管理系统") != -1)
			{
				log.log(Priority.INFO, "登录成功");
				//new HeartThread(manager, "http://fc.js0573.com/zjadmin/top.asp", DEFAULT_CHARSET,"祝您今天工作顺利").start();
				return true;
			}
			log.log(Priority.INFO, "登录失败");
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return login(manager);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		}
		return false;
	}
	
	
	public List<TFcinfo> getFcInfo(HttpClientManager manager, long queryTime,int pageNo)
	{
		List<TFcinfo> list = new ArrayList<TFcinfo>();
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", "http://fc.js0573.com/zjadmin/grcsxxlist.asp?k=&s=1&p=" + pageNo, DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return getFcInfo(manager,queryTime,pageNo);
			}
			String body = new String(wrapper.getBody(),DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@name='frmlist']/table/tbody/tr[@bgcolor='#FFFFFF']");
			if(obj != null && obj.length > 0)
			{
				for(int i = 0; i < obj.length; i++)
				{
					TFcinfo tFcinfo = new TFcinfo();
					TagNode trNode = (TagNode) obj[i];
					Object tds[] = trNode.evaluateXPath("//td/text()");
					if(tds != null && tds.length > 0)
					{
						StringBuffer time = (StringBuffer)tds[9];
						long lastTime = Long.parseLong(DateUtils.dateToString(DateUtils.strToDate(time.toString(), "yyyy-MM-dd HH:mm:ss"), "yyyyMMddHHmmss"));
						if(lastTime > queryTime)
						{
							//当前记录时间在上次查询时间以后， 可以操作。
							tFcinfo.setInfoid(((StringBuffer)tds[0]).toString().trim()); //信息ID
							tFcinfo.setXqld(((StringBuffer)tds[1]).toString().trim()); //小区路段
							tFcinfo.setYt(((StringBuffer)tds[2]).toString().trim()); //用途
							tFcinfo.setLc(((StringBuffer)tds[3]).toString().trim()); //楼层
							tFcinfo.setMj(((StringBuffer)tds[4]).toString().trim()); //面积
							tFcinfo.setQk(((StringBuffer)tds[5]).toString().trim()); //汽库
							tFcinfo.setZk(((StringBuffer)tds[6]).toString().trim()); //自库
							tFcinfo.setZj(((StringBuffer)tds[7]).toString().trim()); //总价
							tFcinfo.setZx(((StringBuffer)tds[8]).toString().trim()); //装修
							tFcinfo.setFbsj(time.toString().trim());
							Object urlObj[] = trNode.evaluateXPath("//td/a");
							TagNode urlNode = (TagNode)urlObj[0];
							tFcinfo.setUrl(urlNode.getAttributeByName("href")); //地址
							tFcinfo.setZt(((StringBuffer)tds[11]).toString().trim()); //状态
							tFcinfo = getLxInfo(manager, tFcinfo);
							list.add(tFcinfo);
						}else{
							break;
						}
					}
				}
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return getFcInfo(manager,queryTime,pageNo);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		return list;
	}
	
	private TFcinfo getLxInfo(HttpClientManager manager, TFcinfo tFcinfo)
	{
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", "http://fc.js0573.com/zjadmin/" + tFcinfo.getUrl(), DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return getLxInfo(manager, tFcinfo);
			}
			String body = new String(wrapper.getBody(),DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@name='form1']/table/tbody/tr");
			if(obj != null && obj.length > 0)
			{
				TagNode trNode = (TagNode)obj[15];
				Object tds[] = trNode.evaluateXPath("/td/text()");
				if(tds != null && tds.length > 0)
				{
					StringBuffer lxinfo = (StringBuffer)tds[1];
					tFcinfo.setLxinfo(lxinfo.toString().trim());
				}
				
				trNode = (TagNode)obj[14];
				tds = trNode.evaluateXPath("/td[@class='tabipt']/textarea[@name='memo']/text()");
				if(tds != null && tds.length > 0)
				{
					StringBuffer bz = (StringBuffer)tds[0];
					tFcinfo.setBz(bz.toString().trim());
				}
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return getLxInfo(manager, tFcinfo);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		return tFcinfo;
	}
	
	public static void main(String args[])
	{
		HttpClientManager manager = new HttpClientManager();
		IFcjs0573Service service = new Fcjs0573ServiceImpl();
		service.login(manager);
		service.getFcInfo(manager, 20120622153644l, 1);
	}
}
